package com.cg.leetcode;

import org.junit.Test;

/**
 * 206.反转链表
 *
 * @program: LeetCode->LeetCode_206
 * @description: 206.反转链表
 * @author: cg
 * @create: 2021-08-31 21:32
 **/
public class LeetCode_206 {

    @Test
    public void test206() {
        ListNode head = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4, new ListNode(5)))));
        System.out.println(reverseList(head));
    }

    /**
     * 给你单链表的头节点 head ，请你反转链表，并返回反转后的链表。
     * <p>
     * 示例 1：
     * 输入：head = [1,2,3,4,5]
     * 输出：[5,4,3,2,1]
     * <p>
     * 示例 2：
     * 输入：head = [1,2]
     * 输出：[2,1]
     * <p>
     * 示例 3：
     * 输入：head = []
     * 输出：[]
     * <p>
     * 提示：
     * 1) 链表中节点的数目范围是 [0, 5000]
     * 2) -5000 <= Node.val <= 5000
     *
     * @param head
     * @return
     */
    public ListNode reverseList(ListNode head) {
        //递归解决
        if (head == null || head.next == null) {
            return head;
        }
        ListNode p = reverseList(head.next);
        head.next.next = head;
        head.next = null;
        return p;
    }
    /*public ListNode reverseList(ListNode head) {
        //迭代解决
        ListNode prev = null;
        ListNode curr = head;
        while (curr != null) {
            ListNode nextTemp = curr.next;
            curr.next = prev;
            prev = curr;
            curr = nextTemp;
        }
        return prev;
    }*/

}
